package com.tuyue.police.api;

import com.tuyue.police.bean.UrlBean;
import com.tuyue.police.enums.ResultEnum;
import com.tuyue.police.exception.MyException;
import com.tuyue.police.response.YsUserResponse;
import com.tuyue.police.util.HttpUtils;
import com.tuyue.police.util.JsonToObject;
import com.tuyue.police.util.MD5;
import com.tuyue.police.util.Result;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 王金海
 * @Description: 子账户操作
 * @Date: Created by Administrator on 2018/6/1.
 * @Modified By:
 */
@Component
public class YsUserApi {

    @Autowired
    private AccessTokenApi accessTokenApi;
    @Value("${appKey}")
    private String appKey;
    /**
     * 创建子账户
     * @param accountName 子账户名
     * @param password 子账户密码 (MD5(AppKey#密码明文))
     * @return accountId 	子账户Id
     */
    public String add(String accountName,String password){
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("accessToken", accessTokenApi.getAccessToken());
        querys.put("accountName", accountName);
        querys.put("password", MD5.md5(appKey+"#"+password));
        HttpResponse response;
        try {
            response = HttpUtils.doPost( UrlBean.ACCOUNTCREATE, querys,null);
            String s = EntityUtils.toString(response.getEntity());
            Result<YsUserResponse> result = JsonToObject.parseObject(s, YsUserResponse.class);
            if (result.getCode()!=200) {
                throw new MyException(result.getCode(),result.getMsg());
            }
            return result.getData().getAccountId();
        } catch (Exception e) {
            throw new MyException(ResultEnum.YS_SERVER_ERROR);
        }
    }
}
